<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="MySQL日志文件主要包含错误日志，慢查询日志，查询日志，binlog、与事务日志(redo,undo)。 本文为了突出重点，将日志文件分成如下两类：普通日志、重点日志（binlog,redo,undo) 1、普通日志1.1、错误日志错误文件，默认为 ${mysql_home}&#x2F;data&#x2F;主机名.err 配置日志文件的参数为 log_error 1show variables like &#39;">
<meta property="og:type" content="article">
<meta property="og:title" content="MySQL技术内幕-InnoDB存储引擎读书笔记(MySQL日志文件)">
<meta property="og:url" content="https://www.codingw.net/posts/3f9b27cb.html">
<meta property="og:site_name" content="中间件兴趣圈">
<meta property="og:description" content="MySQL日志文件主要包含错误日志，慢查询日志，查询日志，binlog、与事务日志(redo,undo)。 本文为了突出重点，将日志文件分成如下两类：普通日志、重点日志（binlog,redo,undo) 1、普通日志1.1、错误日志错误文件，默认为 ${mysql_home}&#x2F;data&#x2F;主机名.err 配置日志文件的参数为 log_error 1show variables like &#39;">
<meta property="og:locale">
<meta property="og:image" content="https://img-blog.csdn.net/20170709102229138?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcHJlc3RpZ2VkaW5n/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center">
<meta property="og:image" content="">
<meta property="og:image" content="https://img-blog.csdn.net/20170709102305468?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcHJlc3RpZ2VkaW5n/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center">
<meta property="og:image" content="">
<meta property="og:image" content="https://img-blog.csdn.net/20170709102338525?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcHJlc3RpZ2VkaW5n/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center">
<meta property="og:image" content="">
<meta property="og:image" content="https://img-blog.csdn.net/20170709102404515?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcHJlc3RpZ2VkaW5n/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center">
<meta property="og:image" content="">
<meta property="og:image" content="https://img-blog.csdn.net/20170709102446664?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcHJlc3RpZ2VkaW5n/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center">
<meta property="og:image" content="">
<meta property="og:image" content="https://img-blog.csdn.net/20170709102605771?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcHJlc3RpZ2VkaW5n/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center">
<meta property="og:image" content="">
<meta property="article:published_time" content="2020-11-15T14:09:01.000Z">
<meta property="article:modified_time" content="2021-04-26T12:32:36.051Z">
<meta property="article:author" content="中间件兴趣圈">
<meta property="article:tag" content="中间件">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img-blog.csdn.net/20170709102229138?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcHJlc3RpZ2VkaW5n/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://www.codingw.net/posts/3f9b27cb.html"/>





  <title>MySQL技术内幕-InnoDB存储引擎读书笔记(MySQL日志文件) | 中间件兴趣圈</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">中间件兴趣圈</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">微信搜『中间件兴趣圈』，回复『Java』获取200本优质电子书</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://www.codingw.net/posts/3f9b27cb.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="中间件兴趣圈">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">MySQL技术内幕-InnoDB存储引擎读书笔记(MySQL日志文件)</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-11-15T22:09:01+08:00">
                2020-11-15
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/mysql/" itemprop="url" rel="index">
                    <span itemprop="name">mysql</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/posts/3f9b27cb.html" class="leancloud_visitors" data-flag-title="MySQL技术内幕-InnoDB存储引擎读书笔记(MySQL日志文件)">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <div id="vip-container"><p>MySQL日志文件主要包含错误日志，慢查询日志，查询日志，binlog、与事务日志(redo,undo)。</p>
<p>本文为了突出重点，将日志文件分成如下两类：普通日志、重点日志（binlog,redo,undo)</p>
<h2 id="1、普通日志"><a href="#1、普通日志" class="headerlink" title="1、普通日志"></a>1、普通日志</h2><h3 id="1-1、错误日志"><a href="#1-1、错误日志" class="headerlink" title="1.1、错误日志"></a>1.1、错误日志</h3><p>错误文件，默认为 ${mysql_home}/data/主机名.err</p>
<p>配置日志文件的参数为 log_error</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">show variables like &#39;%log_error%&#39;;</span><br></pre></td></tr></table></figure>

<h3 id="1-2、慢查询日志"><a href="#1-2、慢查询日志" class="headerlink" title="1.2、慢查询日志"></a>1.2、慢查询日志</h3><p>MySQL判断语句执行慢的参考如下：</p>
<ol>
<li><p>执行时间不能超过 long_query_time(单位为秒，支持到微妙，通过小数点表示)</p>
</li>
<li><p>是否使用了索引开关( log_queries_not_using_indexes 如果设置为1或on,表示如果没有使用索引的语句认为是慢查询 )</p>
</li>
<li><p>本次查询扫描的行数如果小于min_examined_row_limit ,如果本次查收扫描的行数小于该配置值，则不写</p>
</li>
</ol>
<p>​       入慢查询日志。</p>
<ol start="4">
<li>如果没有使用索引，可以控制每分钟出现多少次后才写入一条到慢查询日志中。</li>
</ol>
<blockquote>
<p>参数为： log_throttle_queries_not_using_indexes，默认为0表示不做限制</p>
</blockquote>
<span id="more"></span>

<p>官方文档关于慢查询日志链接：<a target="_blank" rel="noopener" href="https://dev.mysql.com/doc/refman/5.6/en/slow-query-log.html">https://dev.mysql.com/doc/refman/5.6/en/slow-query-log.html</a></p>
<p>根据使用经验，可以使用如下命令查看与慢查询相关的配置属性：</p>
<p><img src="https://img-blog.csdn.net/20170709102229138?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcHJlc3RpZ2VkaW5n/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="img"><img src="" alt="点击并拖拽以移动"></p>
<p><img src="https://img-blog.csdn.net/20170709102305468?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcHJlc3RpZ2VkaW5n/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="img"><img src="" alt="点击并拖拽以移动"></p>
<p><img src="https://img-blog.csdn.net/20170709102338525?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcHJlc3RpZ2VkaW5n/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="img"><img src="" alt="点击并拖拽以移动"></p>
<p><img src="https://img-blog.csdn.net/20170709102404515?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcHJlc3RpZ2VkaW5n/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="img"><img src="" alt="点击并拖拽以移动"></p>
<h3 id="1-3、查询日志"><a href="#1-3、查询日志" class="headerlink" title="1.3、查询日志"></a>1.3、查询日志</h3><p>查询日志官方说明：<a target="_blank" rel="noopener" href="https://dev.mysql.com/doc/refman/5.6/en/query-log.html">https://dev.mysql.com/doc/refman/5.6/en/query-log.html</a></p>
<p>查询日志，详细的记录了所有查询语句对应mysql通信协议语句类型(COM_QUERY)相关的语句执行情况，非常适合定位问题，但生产环境下必须禁用该属性，不然会严重影响性能。查询日志相关的两个属性如下：</p>
<p><img src="https://img-blog.csdn.net/20170709102446664?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcHJlc3RpZ2VkaW5n/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="img"><img src="" alt="点击并拖拽以移动"></p>
<p>既然是COM_QUERY类型的，也包含update,insert语句。</p>
<h2 id="2、binlog、redo、undo"><a href="#2、binlog、redo、undo" class="headerlink" title="2、binlog、redo、undo"></a>2、binlog、redo、undo</h2><p>接下来重点讨论binlog、redo、undo日志</p>
<p>基于InnoDB存储引擎来讨论binlog,redo,undo。</p>
<h3 id="2-1-binlog"><a href="#2-1-binlog" class="headerlink" title="2.1 binlog"></a>2.1 binlog</h3><p>mysql二进制日志，在mysql服务层面记录mysql数据的变化轨迹，其存储格式为基于SQL语句（statement）、基于数据行变化(row)、混合方式(mixed)，其作用主要用来做主从同步。横向类比（Redis主从复制）。</p>
<p>写入时机：下文与redo时一起讨论。</p>
<h4 id="2-1-1-binglog相关参数与解读"><a href="#2-1-1-binglog相关参数与解读" class="headerlink" title="2.1.1 binglog相关参数与解读"></a>2.1.1 binglog相关参数与解读</h4><p>binlog相关的配置参数如下：</p>
<ul>
<li><p>log-bin=mysql-bin  (指定binlog的日志名，默认路径为${mysql_home}/data)</p>
</li>
<li><p>binlog_format 指定binglog的存放格式，statement,row,mixed</p>
</li>
<li><p>max_binlog_size</p>
</li>
<li><p>binlog_cache_size</p>
</li>
<li><p>sync_binlog<br>涉及文件操作，一般的做法是先缓存（内存中），然后隔一段时间将缓存写入到文件中。</p>
<p>binlog的写入同样如此，mysql会为binlog提供一个写缓存区，每个会话将binglog,首先会写入到写缓存区，然后按某种机制刷写到磁盘。</p>
<p>通过max_binlog_size设置单个binlog文件的大小，默认为1G，一个文件达到上限后，再新建一个文件,.index记录了所有的binlog文件。binlog_cache_size,是会话级别的参数，设置binlog的内存缓存区大小，默认为32K。</p>
<p>如果一个会话内的产生的binlog日志超过32K后，mysql会将binglog写入临时的日志文件。mysql提供两个运行时变量binlog_cache_use、binlog_cache_disk_use来记录利用内存缓存和文件缓存的次数。</p>
<p>sync_binlog用来设置输入缓存的频率，表示多少次写缓存区后刷新到磁盘。我们知道，在事务允许过程中，首先会将产生的binlog写入到会话内的缓存区（内存缓存区），然后在事务提交后，将内存缓存区的数据写入到mysql binlog的写缓存区，然后刷写到磁盘，sync_binlog=1表示事务提交时（发出commit之前会先写binlog,但不一定会落盘,InnoDB1.2之后，提交阶段写redo,binlog日志为两阶段提交，见下文详解），将缓存区中的数据立即刷写到磁盘（落盘）。</p>
<p>生产环境下sync_binlog设置为1，保证其数据一致性。但还存在这样一种情况，如果发出事务comit操作，binlog已经被写入，但事务提交过程中，mysql服务器down了，此时会引起主从数据不一致性，该怎么办呢？innodb存储引擎提供了innodb_support_xa=1来解决binlog与innodb存储引擎日志文件不一致的问题（二阶段提交），下午redo,undo部分再详细解读。</p>
</li>
<li><p>binlog-do-db      指定需要同步的数据库(schema)</p>
</li>
<li><p>binlog-ignore-db   指定需要同步（记录binlog）日志的数据库(schema)</p>
</li>
<li><p>log-slave-update   设置从服务器是否也写binglog日志，默认是关闭的,log-slave-update=1表示开启。</p>
</li>
</ul>
<h4 id="2-1-2-binglog工具"><a href="#2-1-2-binglog工具" class="headerlink" title="2.1.2 binglog工具"></a>2.1.2 binglog工具</h4><p>mysql提供了官方的binlog查看工具，mysqlbinlog</p>
<h3 id="2-2-redo与undo日志"><a href="#2-2-redo与undo日志" class="headerlink" title="2.2 redo与undo日志"></a>2.2 redo与undo日志</h3><p>redo与undo是mysql存储引擎级别的日志，俗称事务日志，与事务的实现息息相关。那我们从事务的ACID属性开始说起：</p>
<ul>
<li><p>原子性（Atomicity）<br>事务内的操作要么全部执行，要么全部不执行。</p>
</li>
<li><p>一致性（Consistency）<br>在事务开始之前和事务开始之后，数据库的完整性约束没有被破坏。</p>
</li>
<li><p>隔离性<br>两个事务的执行互不干扰，sql定义了4种隔离级别（读未提交、读已提交、可重复读、串行话读）</p>
</li>
<li><p>持久性（Durability）<br>事务成功执行后，该事务所对数据库所做的变更持久的保存在数据库之中。</p>
</li>
</ul>
<p>redo 重做日志，主要用来保证事务的持久性。</p>
<p>undo 回滚日志，在InnoDB中，将undo看成是数据，并不是日志，存放在数据文件中(innodb表空间文件中ibdata1)。</p>
<h4 id="2-2-1-redo-undo日志基础"><a href="#2-2-1-redo-undo日志基础" class="headerlink" title="2.2.1 redo,undo日志基础"></a>2.2.1 redo,undo日志基础</h4><p><a target="_blank" rel="noopener" href="https://dev.mysql.com/doc/refman/5.7/en/innodb-parameters.html#sysvar_innodb_log_buffer_size">https://dev.mysql.com/doc/refman/5.7/en/innodb-parameters.html#sysvar_innodb_log_buffer_size</a> 官方文档关于InnoDB参数</p>
<p>undo 取消操作，用于事务回滚，将数据恢复到修改之前的状态，InnoDB的多版本并发控制（MVCC）就是基于undo来实现的。undo严格意义上来说，InnoDB将undo信息当成数据，存放在数据文件。数据文件相关的参数如下：</p>
<ul>
<li>innodb_data_home_dir :数据文件的路径，在my.cnf中对应 data_dir</li>
<li>innodb_data_file_path:数据文件名（默认表空间文件）,默认为ibdata1:12M:autoextend</li>
<li>innodb_file_per_table : 支持每个表单独一个表空间文件（数据文件）</li>
<li>innodb_tmpdir      :临时表空间路径</li>
<li>innodb_temp_data_file_path:临时表空间文件，默认为ibtmp1:12M:autoextend</li>
<li>innodb_undo_directory : undo独立目录（undo独立表空间）</li>
<li>innodb_undo_log_truncate:默认为off,undo日志是否支持压缩，删除已经落盘的信</li>
<li>innodb_undo_logs:128,默认为128个undo段，其中0号回滚段存在于默认表空间中，1-32号表空间位于临时表空间。</li>
<li>innodb_undo_tablespaces:默认为0，表示不开启独立的undo表空间。</li>
</ul>
<h5 id="2-2-1-1-redo日志"><a href="#2-2-1-1-redo日志" class="headerlink" title="2.2.1.1 redo日志"></a>2.2.1.1 redo日志</h5><p>重做日志，用来实现服务器异常时的数据恢复，实现事务的持久性。</p>
<p>redo日志的核心思想是使用顺序IO(事务提交时主要写redo日志，操作一个顺序的联系的IO文件)来代替每个事务提交时大量的随机IO去更新数据文件。也就是对数据的修改不会立马刷写到数据文件，而是写入redo文件，然后使用一定的机制，将内存中的脏页异步写入到数据文件，提高事务的执行效率与并发能力。</p>
<p>redo相关的配置参数：</p>
<ul>
<li><p>innodb_log_buffer_size : 一般根据页的大小（8K,16K）设置为8M,16M,写redo日志的缓冲区大小</p>
</li>
<li><p>innodb_log_file_size:单个redo日志文件的大小，默认为48M</p>
</li>
<li><p>innodb_log_files_in_group:默认为2，表示一个redo日志组中包含多少个文件，默认为2个。进行循环覆盖写- </p>
</li>
<li><p>innodb_log_write_ahead_size,每次追加写到redo日志文件的大小，默认为页的大小。8K或16K</p>
</li>
<li><p>innodb_log_group_home_dir:redo日志文件目录，默认为数据文件路径${mysql_home}\data</p>
</li>
</ul>
<h5 id="2-2-1-2-binlog、undo、redo日志写入时机"><a href="#2-2-1-2-binlog、undo、redo日志写入时机" class="headerlink" title="2.2.1.2 binlog、undo、redo日志写入时机"></a>2.2.1.2 binlog、undo、redo日志写入时机</h5><p>redo,重做日志，其引入的目的就是能够回复InnoDB的事务，达到恢复数据的目的。（持久性）</p>
<p>undo回滚日志，其引入的目的就是事务内的回滚(rollback)。（原子性）</p>
<p>redo日志引入的技术性原理分析：</p>
<ul>
<li>数据库存储其底层是文件系统，也就是数据库的数据最终存放在文件中,称之为数据文件。其持久性最通俗的要求就是事务执行后变更要能反馈到数据文件中即可。</li>
</ul>
<p> 操作数据库数据的逻辑一般是这样的：</p>
<ul>
<li>从数据库文件中找到记录，文件一般是按照一种特定的格式存放，比如页，然后加载整页数据到内存，在内存中进行数据的操作（脏页）然后将脏页同步回文件，一般不会立即将脏页刷回到磁盘，这样会产生大量的随机IO操作，性能低下，如果不立即刷回磁盘，那么当服务器挂掉后，存放在内存中的数据会丢失，造成数据的不一致性，也就无从持久化。为了解决这一矛盾，引入了redo日志。</li>
<li>redo日志的引入核心一个思想是采用对redo日志文件的顺序IO来替换频繁的随机IO(更新数据文件)，redo文件使用循环覆写方式。redo一般会有两个文件ib_log0与ib_log1。引入redo日志后，数据库修改数据的通常逻辑为，从数据文件中找到数据页并加载到内存，在内存中修改数据，在事务提交之前先写redo日志，确保redo日志落盘，然后提交事务。数据库中的脏页使用一定的机制，统一刷写到数据文件。这样就将每次事务提交的时候，将随机访问数据文件变成顺序写redo日志。这样就提高了效率。</li>
</ul>
<p>接下来我们以示例来分析，redo,undo是如何写入的。</p>
<ul>
<li>update语句<br>我们知道，InnoDB使用多版本控制并发控制协议(MVCC)来实现无锁的并发读控制，MVCC,就是借助于undo日志。根据MVCC的实现方式，update语句执行逻辑为，先复制一份老的数据，请删除版本号设置为当前的事务ID，然后插入一条新的数据，更新版本号为当前事务。这里复制老的数据这一个步骤完全与undo的引入非常吻合，可以利用undo来恢复数据。那么MVCC结合undo关于update的实现：<ul>
<li>首先将数据（数据行）拷贝一份，将其删除版本号设置为当前事务ID，申请回滚段(undo),记录undo日志,undo日志的存储方式是一条链表（双链表）并且按照事务ID后排序。因为InnoDB把undo日志当成是数据，存放于表空间中，故在写undo之前，需要先写redo日志，redo日志将包含undo信息（可以根据redo日志重建undo日志链）,也就是undo是受redo日志保护的。</li>
<li>然后用插入一条数据，将数据行的更新版本号设置为当前事务。此时继续写redo日志。然后提交事务，此时redo日志落盘，undo日志与数据文件可能还保存在内存中，innodb会按照一定的策略将undo日志和数据脏页写入到磁盘。</li>
</ul>
</li>
</ul>
<p><strong>事务内的查询可见性机制：</strong></p>
<p>我想在事务内根据主键ID查询一条数据应该是先从数据文件中加载该数据，然后判断根据版本号与当前事务ID判断其可见性，如果不可见，则需要从undo链去找，数据文件行中存储了该记录所在的回滚段与偏移量。沿着回滚链找到向前找到第一个符合可见性的记录。</p>
<p>binlog、redo日志的写入关系。</p>
<p>在innodb_support_xa=1与sync_binlog=1时，,innodb会使用二阶段协议来写binlog与redo日志。[innodb_flush_log_at_trx_commit=1]</p>
<p>在mysql服务层发出commit命令后：</p>
<ul>
<li><p>prepare阶段：先写redo日志并落盘(redo日志信息包含undo信息)，状态为prepare。</p>
</li>
<li><p>commit阶段：写binlog文件并落盘</p>
</li>
<li><p>写redo日志并落盘（commit信息）</p>
</li>
</ul>
<p><img src="https://img-blog.csdn.net/20170709102605771?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcHJlc3RpZ2VkaW5n/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="img"><img src="" alt="点击并拖拽以移动"></p>
<p>状态1: Redo Log里存在，Binary Log里也存在 –正常情况，crash恢复时需要commit</p>
<p>状态2: Redo Log里存在，Binary Log里不存在 –prepare完毕后发生crash，恢复时需要rollback</p>
<p>状态3: Redo Log里不存在，Binary Log里也不存在 –提交失败，无需处理</p>
</div>

			<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
			<script>
			var isMobile = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
			if (!isMobile) {
			    var btw = new BTWPlugin();
			    btw.init({
			        "id": "vip-container",
			        "blogId": "18019-1573088808868-542",
			        "name": "中间件兴趣圈",
			        "qrcode": "https://img-blog.csdnimg.cn/20190314214003962.jpg",
			        "keyword": "more"
			    });
			}
			</script>
		
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/5b656c60.html" rel="next" title="MySQL技术内幕-InnoDB存储引擎读写笔记(性能调优)">
                <i class="fa fa-chevron-left"></i> MySQL技术内幕-InnoDB存储引擎读写笔记(性能调优)
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/9d847bb5.html" rel="prev" title="Dubbo路由机制概述">
                Dubbo路由机制概述 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">139</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1%E3%80%81%E6%99%AE%E9%80%9A%E6%97%A5%E5%BF%97"><span class="nav-number">1.</span> <span class="nav-text">1、普通日志</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-1%E3%80%81%E9%94%99%E8%AF%AF%E6%97%A5%E5%BF%97"><span class="nav-number">1.1.</span> <span class="nav-text">1.1、错误日志</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-2%E3%80%81%E6%85%A2%E6%9F%A5%E8%AF%A2%E6%97%A5%E5%BF%97"><span class="nav-number">1.2.</span> <span class="nav-text">1.2、慢查询日志</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-3%E3%80%81%E6%9F%A5%E8%AF%A2%E6%97%A5%E5%BF%97"><span class="nav-number">1.3.</span> <span class="nav-text">1.3、查询日志</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2%E3%80%81binlog%E3%80%81redo%E3%80%81undo"><span class="nav-number">2.</span> <span class="nav-text">2、binlog、redo、undo</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#2-1-binlog"><span class="nav-number">2.1.</span> <span class="nav-text">2.1 binlog</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#2-1-1-binglog%E7%9B%B8%E5%85%B3%E5%8F%82%E6%95%B0%E4%B8%8E%E8%A7%A3%E8%AF%BB"><span class="nav-number">2.1.1.</span> <span class="nav-text">2.1.1 binglog相关参数与解读</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-1-2-binglog%E5%B7%A5%E5%85%B7"><span class="nav-number">2.1.2.</span> <span class="nav-text">2.1.2 binglog工具</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-2-redo%E4%B8%8Eundo%E6%97%A5%E5%BF%97"><span class="nav-number">2.2.</span> <span class="nav-text">2.2 redo与undo日志</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#2-2-1-redo-undo%E6%97%A5%E5%BF%97%E5%9F%BA%E7%A1%80"><span class="nav-number">2.2.1.</span> <span class="nav-text">2.2.1 redo,undo日志基础</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#2-2-1-1-redo%E6%97%A5%E5%BF%97"><span class="nav-number">2.2.1.1.</span> <span class="nav-text">2.2.1.1 redo日志</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#2-2-1-2-binlog%E3%80%81undo%E3%80%81redo%E6%97%A5%E5%BF%97%E5%86%99%E5%85%A5%E6%97%B6%E6%9C%BA"><span class="nav-number">2.2.1.2.</span> <span class="nav-text">2.2.1.2 binlog、undo、redo日志写入时机</span></a></li></ol></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">中间件兴趣圈</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("NNEhOL0iOcflg8f1U3HUqiCq-gzGzoHsz", "7kSmkbbb3DktmHALlShDsBUF");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
